<!doctype html>
<html>
<head>
  <title>文档管理</title>
  <meta  name = "viewport" content = "initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no">
  <script src="webix/webix.js?v=6.4.6" type="text/javascript"></script>
  <script src="filemanager.js?v=6.4.6" type="text/javascript"></script>
  <script src="./base64.js" type="text/javascript"></script>
  <link rel="stylesheet" type="text/css" href="webix/webix.css?v=6.4.6">
  <link rel="stylesheet" type="text/css" href="filemanager.css?v=6.4.6">
  <link rel="stylesheet" href="layui/css/layui.css">
  <script src="layui/layui.js" type="text/javascript"></script>
  <style type="text/css">
    .btn-size-rest{
      height: 32px;
      line-height: 32px;
      padding: 0 15px;
    }
    .input-size-reset {
      width: 240px;
      height:32px;
    }
  </style>
</head>
<body>
<div id="add-main" style="display: none; position: absolute;left:8%">
  <form class="layui-form" id="add-form" action="">
    <div class="layui-form-item center" style="margin-top:15px;">
      <label class="layui-form-label" style="width: 100px" >用户授权:</label>
      <div style="float:left">
        <input type="hidden" name="id" id="id">
        <input type="text" name="userSelect" id="userSelect" placeholder="请选择用户" autocomplete="off" class="layui-input input-size-reset" readonly>
        <input type="hidden" name="userIds" id="userIds">
      </div>
      <div style="margin-left:10px;float:left">
        <button type="button" class="layui-btn btn-size-rest" onclick="selectUser()">选择</button>
        <button type="button" class="layui-btn btn-size-rest" onclick="clearIds(1)">清除</button>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label" style="width: 100px">角色授权:</label>
      <div style="float:left">
        <input type="text" name="roleSelect" id="roleSelect" placeholder="请选择角色" autocomplete="off" class="layui-input input-size-reset" readonly>
        <input type="hidden" name="roleIds" id="roleIds">
      </div>
      <div style="margin-left:10px;float:left">
        <button type="button" class="layui-btn btn-size-rest" onclick="selectRole()">选择</button>
        <button type="button" class="layui-btn btn-size-rest" onclick="clearIds(2)">清除</button>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label" style="width: 100px">组织机构授权:</label>
      <div style="float:left">
        <input type="text" name="value" id="orgSelect" placeholder="请选择组织架构" autocomplete="off" class="layui-input input-size-reset" readonly>
        <input type="hidden" name="orgIds" id="orgIds">
      </div>
      <div style="margin-left:10px;float:left">
        <button type="button" class="layui-btn btn-size-rest" onclick="selectOrg()">选择</button>
        <button type="button" class="layui-btn btn-size-rest" onclick="clearIds(3)">清除</button>
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block" style="margin-left:42%;margin-top: 24px;">
        <button class="layui-btn btn-size-rest" lay-submit lay-filter="save" >确定</button>
        <button type="reset" class="layui-btn btn-size-rest layui-btn-primary" id="closeBtn" >重置</button>
      </div>
    </div>
  </form>
</div>
<div id="select-user" style="display: none;">
  <table id="user_table" lay-filter="user_table" style="height:100%"></table>
</div>
<div id="select-role" style="display: none;">
  <table id="role_table" lay-filter="role_table" style="height:100%"></table>
</div>
<div id="select-org" class="demo-tree-more" style="display: none;"></div>
<div id="select-log" style="display: none;">
  <table id="log_table" lay-filter="log_table" style="height:100%"></table>
</div>
<script type="text/javascript">
  // 获取token
  var token = window.location.search.split('=')[1]
  // 模块化引入 layui
  layui.define(['jquery', 'form', 'table', 'tree', 'util',], function (exports) {
    render()
  })
  function render() {
    var $ = layui.$;
    var form = layui.form;
    var table = layui.table;
    var roleTable = layui.table;
    var tree = layui.tree;
    var util = layui.util;
    form.on('submit(save)', function (data) {
      params = data.field;
      console.log(JSON.stringify(params));
      submit($,params);
      return false;
    });
    //提交
    window.submit = function($,params){
      if (!params.userIds && !params.roleIds && !params.orgIds) {
        layer.msg("请选择授权内容！");
        return;
      }
      $.post('/api/erp/oa/fileManager/auth?token=' + token, params, function (res) {
        if(res){
          layer.msg("授权成功！");
          setTimeout(() => {
            layer.closeAll();
          }, 500)
        }
      }, 'json');
    }

    //选择用户
    window.selectUser = function(){
      layer.open({
        type: 1,
        title:"选择用户",
        shift: 2,
        area: ['700px', '600px'],
        content: $("#select-user"),
        btn: ['确定', '取消'],
        success:function(){
          var id = $("#id").val();
          table =  $.extend(table, {config: {checkName: 'checked'}});
          table.render({
            elem: '#user_table'
            ,url: '/api/erp/oa/fileManager/userList?id=' + id + '&token=' + token
            ,method : 'get'
            ,response : {
              statusName : 'code'
              ,statusCode : 200
              ,msgName : 'msg'
              ,countName : 'total'
              ,dataName : 'data'
            }
            ,title : '用户列表'
            ,cols : [[
              {type:'checkbox'}
              ,{ field : 'username', title : '用户账号', width : 190,align:'center'}
              ,{ field : 'title', title : '真实姓名', width : 190,align:'center' }
              ,{ field : 'email', title : '邮箱', width : 220,align:'center' }
            ]]
            ,page: true
          });
        },
        yes:function(index){
          var checkStatus = table.checkStatus('user_table');
          var data = checkStatus.data;
          var temp = '';
          var idstr = '';
          for(var i=0;i<data.length;i++){
            temp += ',' + data[i].title;
            idstr += ',' + data[i].id;
          }
          $('#userSelect').val(temp.substring(1));
          $('#userIds').val(idstr.substring(1));
          layer.close(index);
        }
      });
    }
    //选择角色
    window.selectRole = function(){
      layer.open({
        type: 1,
        title:"选择角色",
        shift: 2,
        area: ['700px', '600px'],
        content: $("#select-role"),
        btn: ['确定', '取消'],
        success:function(){
          var id = $("#id").val();
          roleTable =  $.extend(roleTable, {config: {checkName: 'checked'}});
          roleTable.render({
            elem: '#role_table'
            ,url: '/api/erp/oa/fileManager/roleList?id=' + id + '&token=' + token
            ,method : 'get'
            ,response : {
              statusName : 'code'
              ,statusCode : 200
              ,countName : 'total'
              ,msgName : 'msg'
              ,dataName : 'data'
            }
            ,title : '角色列表'
            ,cols : [[
              {type:'checkbox'}
              ,{ field : 'title', title : '角色名称', width : 300,align:'center' }
              ,{ field : 'roleCode', title : '角色编码', width : 300,align:'center' }
            ]]
            ,page: true
          });
        },
        yes:function(index){
          var checkStatus = table.checkStatus('role_table');
          var data = checkStatus.data;
          var temp = '';
          var idstr = '';
          for(var i=0;i<data.length;i++){
            temp += ',' + data[i].title;
            idstr += ',' + data[i].id;
          }
          $('#roleSelect').val(temp.substring(1));
          $('#roleIds').val(idstr.substring(1));
          layer.close(index);
        }
      });
    }
    //部门
    window.selectOrg = function(){
      layer.open({
        type: 1,
        title:"选择组织架构",
        closeBtn: 1,
        shift: 2,
        area: ['700px', '600px'],
        content: $("#select-org"),
        btn: ['确定', '取消'],
        success:function(){
          var id = $("#id").val();
          $.get('/api/erp/oa/fileManager/departList?id=' + id + '&token=' + token, function (res) {
            if(res){
              tree.render({
                elem: '#select-org'
                ,icon: 'layui-icon layui-icon-group'
                ,data: res
                ,showCheckbox: true  //是否显示复选框
                ,id: 'demoId1'
                ,isJump: false //是否允许点击节点时弹出新窗口跳转
              });
            }
          }, 'json');
        },
        yes:function(index){
          var temp = '';
          var idstr = '';
          var checkedData = tree.getChecked('demoId1'); //获取选中节点的数据
          for(var i=0;i<checkedData.length;i++){
            //递归调用
            idstr += ',' + checkedData[i].id;
            temp += ',' + checkedData[i].title;
            if(checkedData[i].children.length > 0){
              var arr = getCheckedVal(idstr,temp,checkedData[i].children);
              if(arr){
                idstr = arr[0];
                temp = arr[1];
              }
            }
          }
          $('#orgSelect').val(temp.substring(1));
          $('#orgIds').val(idstr.substring(1));
          layer.close(index);
        }
      });
    }
    //递归获取id、title
    window.getCheckedVal = function(idstr,temp,data){
      var arr = [];
      for(var i=0;i<data.length;i++){
        //递归调用
        idstr += ',' + data[i].id;
        temp += ',' + data[i].title;
        if(data[i].children && data[i].children.length > 0){
          getCheckedVal(idstr,temp,data[i].children);
        }
      }
      arr[0] = idstr;
      arr[1] = temp;
      return arr;
    }
    window.clearIds = function(val){
      if(val === 1){
        $('#userSelect').val("");
        $('#userIds').val("");
      }else if(val === 2){
        $('#roleSelect').val("");
        $('#roleIds').val("");
      }else{
        $('#orgSelect').val("");
        $('#orgIds').val("");
      }
    }

    window.fileUrl = "/api/erp/oa/fileManager/list?token=" + token

    webix.ready(function(){
      var selectId = "";
      webix.ui({
        view: "filemanager",
        id: "files",
        url: window.fileUrl,
        handlers:{
          "create": "/api/erp/oa/fileManager/create?token=" + token,
          "rename": "/api/erp/oa/fileManager/rename?token=" + token,
          "move": "/api/erp/oa/fileManager/move?token=" + token,
          "upload" : "/api/erp/oa/fileManager/upload?token=" + token,
          "download": "/api/erp/oa/fileManager/download?token=" + token,
          "remove": "/api/erp/oa/fileManager/remove?token=" + token,
        },
        on:{
          "onViewInit": function(name, config){
            if (name == "table"){
              var columns = config.columns;
              var newColumn1 = {id: "downCount",
                header:"下载次数",
                fillspace: 1,
                template: function(obj,common){
                  if(obj.type === 'folder') return '';
                  else return obj.downCount === undefined?0:obj.downCount;
                }
              };
              webix.toArray(columns).insertAt(newColumn1,2);
              var newColumn2 = {id: "readCount",
                header:"阅读次数",
                fillspace: 1,
                template: function(obj,common){
                  if(obj.type === 'folder') return '';
                  else return obj.readCount === undefined?0:obj.readCount;
                }
              };
              webix.toArray(columns).insertAt(newColumn2,3);
            }
          }
        },
        ready:function(){
          this.getMenu().add({
            id: "preview",
            icon: "webix_icon wxi-search",
            value: "预览",
            batch: "file",
            method:"previewFile"
          }, 0);
          this.getMenu().add({
            id: "auth",
            icon: "webix_icon wxi-user",
            value: "授权",
            method:"authFile"
          }, 1);
          this.getMenu().add({
            id: "showlog",
            icon: "webix_icon wxi-search",
            value: "查看日志",
            batch: "file",
            method:"authFile"
          }, 2);
          this.getMenu().add({
            id: "download",
            icon: "webix_icon wxi-download",
            value: "下载",
            batch: "file",
            method:"download"
          }, 7);
          this.getMenu().add({
            id: "create-root-folder",
            icon: "fm-folder",
            value: "创建根目录",
            batch: "root",
            method:"createRootFolder"
          }, 4);
        }
      });
      //双击文件下载提示
      $$("files").attachEvent("onBeforeRun",function(id){
        webix.confirm({
          text:"是否下载该文件?",
          ok:"是",
          cancel:"否",
          callback:function(result){
            if (result) {
              $$('files').download(id)
              $$("files").load(window.fileUrl).then(function (){
                $$("files").refreshCursor()
              })
            }
          }
        });
        return false;
      });
      //获取菜单，添加授权、预览按钮
      var actions = $$("files").getMenu();
      actions.attachEvent("onItemClick", function(id, e, node){
        selectId = $$("files").getActive();
        if(id == "auth"){
          if (!selectId) {
            layer.msg("请选择文件夹或文件！");
            return;
          }
          if (selectId instanceof Array) {
            layer.msg("暂不支持批量授权！");
            return;
          }
          layer.open({
            type: 1,
            title:"授权",
            shift: 2,
            area: ['700px', '400px'],
            content: $("#add-main"),
            success: function(layero, index){
              $("#id").val(selectId);
              if (selectId instanceof Array) {
                selectId = selectId.join(',');
              }
              webix.ajax().put("/api/erp/oa/fileManager/initAuth?id=" + selectId + "&token=" + token,function(data) {
                var res = JSON.parse(data);
                if(res.success){
                  var result = res.result;
                  //初始化授权输入框
                  $("#userSelect").val(result.userNames?result.userNames:null);
                  $('#userIds').val(result.userIds?result.userIds:null);
                  $('#roleSelect').val(result.roleNames?result.roleNames:null);
                  $('#roleIds').val(result.roleIds?result.roleIds:null);
                  $('#orgSelect').val(result.departNames?result.departNames:null);
                  $('#orgIds').val(result.departIds?result.departIds:null);
                }
              });
            }
          });
        }else if(id == "preview"){
          if (selectId instanceof Array) {
            layer.msg('暂不支持批量预览！')
            return;
          }
          webix.ajax().get(`/api/erp/oa/fileManager/preview?id=${selectId}&token=${token}`, function (data) {
            data = JSON.parse(data);
            if (data.contentType.indexOf('image') !== -1) {
              layer.open({
                type: 1,
                title:"图片预览",
                shift: 2,
                content: `<img src="/api/erp/oa/fileManager/previewFile?id=${selectId}&token=${token}"/>`,
                area: ['750px', '600px'],
                btn: ['取消']
              });
            } else {
              var fileUrl = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + data.url
              var url = window.sessionStorage.getItem('onLineUrl') + '?url=' + encodeURIComponent(Base64.encode(fileUrl));
              window.open(url);
              // window.open(`/api/erp/oa/fileManager/previewFile?id=${selectId}&token=${token}`)
              
            }
          })
        }else if(id == "showlog"){
          if (selectId instanceof Array) {
            layer.msg('暂不支持批量查看日志！')
            return;
          }
          layer.open({
            type: 1,
            title:"文件日志",
            shift: 2,
            content: $("#select-log"),
            area: ['750px', '600px'],
            btn: ['取消'],
            success:function(){
              table =  $.extend(table, {config: {checkName: 'checked'}});
              table.render({
                elem: '#log_table'
                ,url: '/api/erp/oa/fileManager/log/list?id=' + selectId + '&token=' + token
                ,method : 'get'
                ,response : {
                  statusName : 'code',
                  statusCode : 200,
                  msgName : 'msg',
                  countName : 'total',
                  dataName : 'data'
                }
                ,title : '日志列表'
                ,cols : [[
                  { type:"numbers",title:"#", width:80,align:'center'},
                  { field:"username",title:"用户", width:200,align:'center'},
                  { field:"operateType",title:"操作类型",width:200,templet: function(d){
                      var type = d.operateType;
                      if(type === '1') return "创建";
                      if(type === '2') return "编辑";
                      if(type === '3') return "删除";
                      if(type === '4') return "查看";
                      if(type === '5') return "下载";
                    },align:'center'},
                  { field:"operateTime",	title:"操作时间",width:200,align:'center'}
                ]]
                ,limits: [10, 20, 50]
                ,limit: 10
                ,page: true
              });
            }
          });
        }
      });
    });
  }
</script>
</body>
</html>